<?php defined('BASEPATH') or exit('No direct script access allowed');

class Infostreams_m extends MY_Model
{
    
    public $infostream;
    public $infostream_fields;

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper('cookie');
        $this->load->helper('date');

        $this->load->driver('Streams');

        date_default_timezone_set('Europe/Kiev');
        
        // Get the user ID, if it exists
        if($this->ion_auth->logged_in())
        {
            $this->user_id = $this->current_user->id;
        }

        $this->infostream = $this->streams_m->get_stream('infostream', true, 'streams');
        $this->infostream_fields = $this->streams_m->get_stream_fields($this->
            infostream->id);

        $this->events_stream = $this->streams_m->get_stream('events', true, 'streams');
        $this->events_fields = $this->streams_m->get_stream_fields($this->events_stream->id);
        
        $this->notices_stream = $this->streams_m->get_stream('notices', true, 'streams');
        $this->notices_fields = $this->streams_m->get_stream_fields($this->notices_stream->id);
            
        
    }
	
	public function get_Infostreams($infostream_id = 0)
    {
        //$this->db->where('infostream_id', $infostream_id);
        $data = $this->streams_m->get_stream_data($this->infostream, $this->
            infostream_fields);
        
		// Get the entries
        //$events = $this->db->get($this->events_stream->stream_prefix.$this->events_stream->stream_slug)->result();
           
		foreach($data as &$row):
			$row->_events = array();
			if(!empty($row->created_by))
			{
				$row->created_by['avatar'] = gravatar($row->created_by['email']);
			}	
			
			/*
			//События
            if($events)
            {
                foreach ($events as $ev_row) {
                    if($ev_row->infostream_id == $row->id)
                    {
                        //Комменты
                        //$ev_row->comments = display_comments($ev_row->id, 'infostreams/tree');
                        $ev_row->_count_comments = 1;
                        $ev_row->_count_notices = 0;
            
                        $row->_events[] = $ev_row;
                    }
                }
            }
			*/
			
            //Признак редактирования ответственным
            $row->_is_creator = false;
            if( $this->ion_auth->logged_in() AND empty($row->created_by) == FALSE AND ($row->created_by['user_id'] == $this->user_id) )
            //if( $this->ion_auth->logged_in()  )
            {
                $row->_is_creator = true;    
            }
            
            //Израсходовано времени
            $row->spent_time = 0;
            $date_completion = strtotime(sprintf('%s %s:%s:%s', $row->date_completion, 23, 59, 59));
            if($date_completion > 0){
                $all_time = DateDiff('d', $row->created, $date_completion);
                $time_left = DateDiff('d', time(), $date_completion);
                $row->all_time = $all_time;
                $row->time_left = $time_left;
                $row->spent_time = 100 - round($time_left/$all_time*100);
                if($date_completion < time()){
                    $row->spent_time = 100;
                }    
            }
        
            //Устанавливаем параметры
            $row->_contains_notice = true;
			
		endforeach;
		   
        //$data = $this->db->get($this->infostream->stream_prefix.$this->infostream->stream_slug)->result();
        
        return $data;

    }
	
    function getInfoStreams($where)
    {

        if (!is_array($where)) {
            $where = array('id' => $where);
        }

        return $this->db->select('*')->where($where)->order_by('created_on', 'ASC')->
            get('InfoStreams')->result();

    }

    function getPropertyValues($where)
    {


        if (!is_array($where)) {
            $where = array('id' => $where);
        }

        $InfoStreams = $this->db->select('  InfoStreams.id          AS stream_id, 
                        InfoStreams.source_id   AS source_id, 
                        InfoStreams.identifier  AS identifier, 
                        InfoStreams.created_on  AS created_on, 
                        InfoStreams.title       AS title, 
                        InfoStreams.status      AS status, 
                        PropertyValues.id          AS value_id,
                        PropertyValues.property_id AS property_id,
                        PropertyValues.value       AS value')
                        ->join('ISPropertyValues AS PropertyValues', 'PropertyValues.object_id = InfoStreams.id', 'left')
                        ->join('ISPropertiesObjects AS PropertiesObjects', 'PropertiesObjects.id = PropertyValues.property_id', 'left')
                        ->where($where)
                        ->order_by('InfoStreams.created_on', 'ASC')
                        ->order_by('PropertiesObjects.sort', 'ASC')
                        ->order_by('PropertyValues.property_id', 'ASC')
            ->get('InfoStreams')->result();

        $PropertiesObjects = $this->db->select('*')->order_by('sort', 'ASC')->get('ISPropertiesObjects')->
            result();


        $InfoStreamsObjects = array();

        foreach ($InfoStreams as $row):

            $InfoStreamsObjects[$row->stream_id][] = $row;

        endforeach;

        unset($InfoStreams);

        $stStreams = array();

        foreach ($InfoStreamsObjects as $stream_id => $InfoStreamsRows):

            $curStreams = &$stStreams;

            $i = 0;

            foreach ($PropertiesObjects as $Prop):

                foreach ($InfoStreamsRows as $row):

                    if ($row->property_id == $Prop->id):

                        $color = null;

                        if (isset($curStreams[$row->value]) == false):

                            $curStreams[$row->value] = array(
                                'value' => $row->value,
                                'name' => $Prop->name,
                                'color' => $color,
                                'level' => $i,
                                'childs' => array());

                        endif;

                        if ($row->status == 'close') {
                            $curStreams[$row->value]['color'] = "#ccc";
                        } elseif ($row->status == 'update') {
                            $curStreams[$row->value]['color'] = "#f9f0ab";
                        } else {
                            $curStreams[$row->value]['color'] = "#0099FF";
                        }


                        $curStProperty = &$curStreams[$row->value];
                        $curStreams = &$curStProperty['childs'];

                    endif;

                endforeach;

                $i++;

            endforeach;

        endforeach;

        unset($InfoStreamsObjects);
        unset($PropertiesObjects);

        return $stStreams;

    }

    public function get_InfostreemTree($parent_id = 0)
    {
        //$this->db->where('created_by', $this->user_id);
        $data = $this->streams_m->get_stream_data($this->infostream, $this->
            infostream_fields);
           
        $level = 0;
            
        $parentdata = array();
        $cur_row = false;
        if($data):
            foreach($data as $row):
                $parentdata[$row->parent][] = $row;
                if($row->id == $parent_id):
                    //$cur_row = $row;  
                    $level = $row->level + 1;   
                endif;
            endforeach;
        endif;
         
        //$events = $this->streams_m->get_stream_data($events_stream, $events_fields);
        // Get the entries
        $events = $this->db->get($this->events_stream->stream_prefix.$this->events_stream->stream_slug)->result();
            
         /*       
        if($cur_row !== false){
            $level = $cur_row->level++;
        }else{
            $level = 0;    
        }
        */

        return $this->build_tree($parentdata, $parent_id, $level, $events);

    }

    private function build_tree($data, $parent_id, $level, $events, $i =0)
    {   
     
       $tree = array();
       if($i > 1000) return $tree;
       if (is_array($data) and (isset($data[$parent_id])) and count($data[$parent_id]) > 0):
            foreach ($data[$parent_id] as $row):
                if($row->level == $level):
                    $tree[$row->id] = $row; 
                    $tree[$row->id]->_is_last_level = (isset($data[$row->id]) ? false : true); $i++;
                    $tree[$row->id]->_events = array();
					if(!empty($tree[$row->id]->created_by))
					{
						$tree[$row->id]->created_by['avatar'] = gravatar($tree[$row->id]->created_by['email']);
					}
					
                    //Это последний уровень дерева
                    $is_last_level = true;
                    if(isset($data[$row->id])){
                        foreach ($data[$row->id] as $key => $value) {
                            if($value->level > $row->level){
                                $is_last_level = false;
                                break;
                            }
                        }
                    }

                    //События
                    if($events)
                    {
                        foreach ($events as $ev_row) {
                            if($ev_row->infostream_id == $row->id)
                            {
                                //Комменты
                                //$ev_row->comments = display_comments($ev_row->id, 'infostreams/tree');
                                $ev_row->_count_comments = 1;
                                $ev_row->_count_notices = 0;
                    
                                $tree[$row->id]->_events[] = $ev_row;
                            }
                        }
                    }

                    //Признак редактирования ответственным
                    $tree[$row->id]->_is_creator = false;
                    if( $this->ion_auth->logged_in() AND empty($tree[$row->id]->created_by) == FALSE AND ($tree[$row->id]->created_by['user_id'] == $this->user_id) )
                    //if( $this->ion_auth->logged_in()  )
                    {
                        $tree[$row->id]->_is_creator = true;    
                    }
                    
                    //Израсходовано времени
                    $tree[$row->id]->spent_time = 0;
                    $date_completion = strtotime(sprintf('%s %s:%s:%s', $tree[$row->id]->date_completion, 23, 59, 59));
                    if($date_completion > 0){
                        $all_time = DateDiff('d', $tree[$row->id]->created, $date_completion);
                        $time_left = DateDiff('d', time(), $date_completion);
                        $tree[$row->id]->all_time = $all_time;
                        $tree[$row->id]->time_left = $time_left;
                        $tree[$row->id]->spent_time = 100 - round($time_left/$all_time*100);
                        if($date_completion < time()){
                            $tree[$row->id]->spent_time = 100;
                        }    
                    }
                
                    //Устанавливаем параметры
                    $tree[$row->id]->_contains_notice = true;
                    $tree[$row->id]->_is_last_level = $is_last_level;
                    $tree[$row->id]->_childs = $this->build_tree($data, $row->id, $level, $events, $i);
                    
                endif;
            endforeach;
        endif;
        
		/*
	    $result=mysql_query("SELECT id, parent_id, title FROM tree");
	    $cats = array();
	    while($cat =  mysql_fetch_assoc($result))
	    $cats[$cat['parent_id']][] =  $cat;
	    
	    function  build_tree($cats,$parent_id){
	    if(is_array($cats) and count($cats[$parent_id])>0){
	    $tree = '<ul>';
	    foreach($cats[$parent_id] as $cat){
	    $tree .= '<li>'.$cat['title'];
	    $tree .=  build_tree($cats,$cat['id']);
	    $tree .= '</li>';         
	    }
	    $tree .= '</ul>';
	    } 
	    else return null;          
	    return $tree; 
	    }
	    echo build_tree($cats,0); // :)))   
	    */
    
        return $tree;
    }
    
    public function Add($post)
    {
        if ( ! $result_id = $this->row_m->insert_entry($post, $this->infostream_fields, $this->infostream, array()))
		{
		  return 0;
        } else {
            
            return $result_id;
        }
			
    }

    public function getLevelParent($parent_id)
    {
        //$this->db->where('id', $parent_id);
        $data = $this->streams_m->get_stream_data($this->infostream, $this->
            infostream_fields);
        
        $level = 0;
        if(sizeof($data) > 0):
        //    $level = $data[0]->level;
        //endif;
        //if(is_array($data)):
            foreach($data as $row):
                if($row->id == $parent_id):
                    $level = $row->level;    
                    break;
                endif;
            endforeach;
        endif;

        return $level;         
        
    }

    public function delete($id)
    {
        return $this->row_m->delete_row($id, $this->infostream);   
    }
    
    public function update($id, $post)
    {
		$skips = array();
		foreach ($this->infostream_fields as $field)
		{
			if(!isset($post[$field->field_slug])){
				$skips[] = $field->field_slug;	
			}
		}
		
        return $this->row_m->update_entry($this->infostream_fields, $this->infostream, $id, $post, $skips);
    }

    public function check_version($id, $version)
    {
        $this->db->where('id', $id);
        $data = $this->streams_m->get_stream_data($this->infostream, $this->
            infostream_fields);
        
        $version = $version + 0;

        return $this->is_version_correct($data, $version);         
        
    }
    
    public function check_version_event($id, $version)
    {
        $this->db->where('id', $id);
        $data = $this->streams_m->get_stream_data($this->events_stream, $this->
            events_fields);
        
        $version = $version + 0;
                
        return $this->is_version_correct($data, $version);
    }

    private function is_version_correct($data, $version)
    {

        $check_version = false;
        if(sizeof($data) > 0):
            foreach($data as $row):
                if($version == $row->version):
                    $check_version = true;
                    break;
                endif;
            endforeach;
        endif;
        
        return $check_version; 
    }

    public function check_user($id)
    {
        if (!$this->ion_auth->logged_in())
        {
            return false;
        }

        $this->db->where('id', $id);
        $data = $this->streams_m->get_stream_data($this->infostream, $this->
            infostream_fields);
        
        return $this->is_user_correct($data);         
        
    }
    
    public function check_user_events($id)
    {
        if (!$this->ion_auth->logged_in())
        {
            return false;
        }

        $this->db->where('id', $id);
        $data = $this->streams_m->get_stream_data($this->events_stream, $this->
            events_fields);
        
        return $this->is_user_correct($data);         
        
    }
    
    public function check_user_comments($id)
    {
        if (!$this->ion_auth->logged_in())
        {
            return false;
        }

        $check_user = false;
        
        $reference = 'infostreams';
        $ref_id = $id;
        
        $comment = $this->comments_m->get($id);
        if($this->user_id == $comment->user_id):
            $check_user = true;
        endif;
    
        return $check_user;         
        
    }
    
    private function is_user_correct($data)
    {

        $check_user = false;
        if(sizeof($data) > 0):
            foreach($data as $row):
                if($this->user_id == $row->created_by['user_id']):
                    $check_user = true;
                    break;
                endif;
            endforeach;
        endif;
        
        return $check_user; 
    }

    public function get_Events($infostream_id = 0)
    {
        $this->db->where('infostream_id', $infostream_id);
        //$data = $this->streams_m->get_stream_data($this->events_stream, $this->
        //    events_fields);
           
        $events = $this->db->get($this->events_stream->stream_prefix.$this->events_stream->stream_slug)->result();
        
        return $events;

    }

    public function AddEvent($post)
    {
        if ( ! $result_id = $this->row_m->insert_entry($post, $this->events_fields, $this->events_stream, array()))
        {
          return 0;
        } else {
            
            return $result_id;
        }
            
    }
    
    public function DeleteEvent($id)
    {
        return $this->row_m->delete_row($id, $this->events_stream);   
    }
    
    public function UpdateEvent($id, $post)
    {
        $skips = array();
        foreach ($this->events_fields as $field)
        {
            if(!isset($post[$field->field_slug])){
                $skips[] = $field->field_slug;  
            }
        }
        
        return $this->row_m->update_entry($this->events_fields, $this->events_stream, $id, $post, $skips);
    }

    public function DeleteComment($where)
    {
     
        if(!is_array($where))
        {
            $where = array('id' => $where);
        }
        
        return $this->db->delete('comments', $where);
    }

    public function getNotices($where)
    {
        //$this->db->where('module',    $module);
        //$this->db->where('module_id', $module_id);
        //$this->db->where('user_id',   $this->user_id);
        
        if (!is_array($where)) {
            $where = array('id' => $where);
        }

        $this->db->where($where);
        
        //$data = $this->streams_m->get_stream_data($this->notices_stream, $this->
        //    notices_fields);
           
        $events = $this->db->get($this->notices_stream->stream_prefix.$this->notices_stream->stream_slug)->result();
        
        return $events;

    }

    public function AddNotice($post)
    {
        if ( ! $result_id = $this->row_m->insert_entry($post, $this->notices_fields, $this->notices_stream, array()))
        {
          return 0;
        } else {
            
            return $result_id;
        }
            
    }
    
    public function DeleteNotice($id)
    {
        return $this->row_m->delete_row($id, $this->notices_stream);   
    }

    public function get($id)
    {
        $this->db->where('id', $id);
           
        return $this->db->get($this->events_stream->stream_prefix.$this->events_stream->stream_slug)->row();
        

    }
}

?>